package com.appfront;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android_serialport_api.SerialPort;

import com.appfront.debug.App;
import com.auxtools.CrashHandler;
import com.auxtools.CreatePDF;
import com.auxtools.LINE;
import com.rtuwrapper.connection.ModbusRtuConnection;
import com.rtuwrapper.io.ModbusRtuTransaction;
import com.rtuwrapper.messaging.ModbusException;
import com.rtuwrapper.messaging.ReadIntegerRequest;
import com.rtuwrapper.messaging.ReadIntegerResponse;
import com.rtuwrapper.messaging.WriteRegisterRequest;
import com.rtuwrapper.messaging.WriteRegisterResponse;
import com.uicontrol.InputFilterMinMax;
import com.uicontrol.RoundProgressBar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.view.LineChartView;

import static com.rtuwrapper.ModbusConstants.VENDOR_ID;

public class LoginActivity extends Activity {

    private static final int REQUEST_CODE = 1;   //请求码
    TextView    textView_title;
    /* modbus 管理类*/
    static public ModbusRtuConnection connection;
    static public ModbusRtuTransaction transaction;
    static public boolean isConnected = false;
    /* 自由/专业选择 */
    Button button_freedom;
    Button button_profession;
    LinearLayout layout_freedom;
    LinearLayout layout_profession;
    /* 专业设置界面空间 */
    EditText editText_userID;
    RadioButton radioButton_male;
    RadioButton radioButton_female;
    EditText editText_userAge;
    EditText editText_userHeight;
    EditText editText_userWeight;
    Spinner spinner_plan;
    /* 专业设置界面初始力 */
    TextView    initForce_text;
    SeekBar     initForce_bar;
    Switch      initForce_switch;
    /* 专业设置界面功能按钮 */
    Button start_button;
    Button setup_button;
    Button query_button;
    Button back_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_login);

        textView_title = (TextView) findViewById(R.id.login_title);
        /* 布局切换页面 */
        layout_freedom = (LinearLayout) findViewById(R.id.layout_freedom);
        layout_profession = (LinearLayout) findViewById(R.id.layout_profession);
        button_freedom = (Button) findViewById(R.id.login_freedom);
        button_profession = (Button) findViewById(R.id.login_profession);
        back_button = (Button) findViewById(R.id.login_back);
        /* 专业模式控件 */
        start_button = (Button) findViewById(R.id.login_start);
        setup_button = (Button) findViewById(R.id.login_setup);
        query_button = (Button) findViewById(R.id.login_query);
        editText_userID = (EditText) findViewById(R.id.login_userID);
        radioButton_male = (RadioButton) findViewById(R.id.login_male);
        radioButton_female = (RadioButton) findViewById(R.id.login_female);
        radioButton_female.setChecked(false);
        radioButton_male.setChecked(true);
        editText_userAge = (EditText) findViewById(R.id.login_userAge);
        editText_userAge.setFilters(new InputFilter[]{new InputFilterMinMax(1,200)});
        editText_userHeight = (EditText) findViewById(R.id.login_userHeight);
        editText_userHeight.setFilters(new InputFilter[]{new InputFilterMinMax(1,300)});
        editText_userWeight = (EditText) findViewById(R.id.login_userWeight);
        editText_userWeight.setFilters(new InputFilter[]{new InputFilterMinMax(1,500)});
        spinner_plan = (Spinner) findViewById(R.id.login_spinner_plan);
        /* 专业模式-初始力设置控件 */
        initForce_text = (TextView) findViewById(R.id.login_initForceText);
        initForce_bar  = (SeekBar) findViewById(R.id.login_initForceBar);
        initForce_switch = (Switch) findViewById(R.id.login_initForceSwitch);

        App.VerifyStoragePermissions(this);     // 申请存储权限
        layout_switchShow(false);               // 切换到自由选择模式
        initLineChart();                                // 初始化左侧曲线图
        /* 自由康复模式按钮点击 */
        button_freedom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TestproSetup.usrID = "";
                TestproSetup.setCurFreqs(10);
                TestproSetup.setCurGroup(1);
                startOneTest();
            }
        });
        /* 专业康复模式按钮点击 */
        button_profession.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_switchShow(true);
            }
        });
        /* 返回模式选择 */
        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_switchShow(false);
            }
        });

        /* 查询导出按钮 */
        query_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent fileChooserIntent = new Intent(LoginActivity.this , FileChooserActivity.class);
                startActivityForResult(fileChooserIntent , REQUEST_CODE);
            }
        });
        /* 开始测试按钮 */
        start_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TestproSetup.usrID = editText_userID.getText().toString();
                TestproSetup.isMale = radioButton_male.isChecked();
                if(editText_userAge.getText().toString().length() > 0)
                    TestproSetup.userAge = Integer.parseInt(editText_userAge.getText().toString());
                else
                    TestproSetup.userAge = -1;
                if(editText_userHeight.getText().toString().length() > 0)
                    TestproSetup.userHeight = Integer.parseInt(editText_userHeight.getText().toString());
                else
                    TestproSetup.userHeight = -1;
                if(editText_userWeight.getText().toString().length() > 0)
                    TestproSetup.userWeight = Integer.parseInt(editText_userWeight.getText().toString());
                else
                    TestproSetup.userWeight = -1;
                if(editText_userID.getText().length() == 0){
                    showNormalDialog();
                }else{
                    startOneTest();
                }
            }
        });
        /* 开始调试按钮 */
        textView_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, MainActivityDebug.class);
                LoginActivity.this.startActivity(intent);
            }
        });
        /* 修改测试方案按钮点击 */
        setup_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TestproSetup.currentPlan = spinner_plan.getSelectedItemPosition()+1;
                TestproSetup.LoadSetup();   //读取配置文件
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, SetupActivity.class);
                LoginActivity.this.startActivity(intent);
            }
        });

        /* 打开串口，进行连接 */
        connection = new ModbusRtuConnection(getApplicationContext(), VENDOR_ID, false);
        connection.connect(new ModbusRtuConnection.OnConnectedToPlcListener() {
            @Override
            public void onConnected(boolean connected, boolean isUSBDevice) {
                if (true == connected) {
                    Toast.makeText(App.getContext(), "设备连接成功", Toast.LENGTH_SHORT).show();
                    isConnected = true;
                    transaction = new ModbusRtuTransaction(LoginActivity.connection, isUSBDevice);
                }else{
                    isConnected = false;
                }
            }
        });

        initForce_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int last_progress = 0;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(last_progress != progress){
                    initForce_switch.setChecked(false);
                }
                initForce_text.setText("初始力：" + progress + "N");
                last_progress = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        /* 设置初始力值按钮点击 */
        initForce_switch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    try {
                        WriteRegisterRequest request = new WriteRegisterRequest();
                        WriteRegisterResponse response;
                        request.setData(4, initForce_bar.getProgress());
                        try {
                            LoginActivity.transaction.execute(request);
                        } catch (ModbusException e) {
                            App.toast("request err: " + e.toString(), App.DEBUG_LEVEL.WARN);  //e.printStackTrace();
                        }
                        try {
                            response = (WriteRegisterResponse) LoginActivity.transaction.getResponse();
                            int realValue = response.getValue();
                            App.toast("respone: " + realValue + "N", App.DEBUG_LEVEL.INFO);
                        } catch (ModbusException e) {
                            App.toast("response err: " + e.toString(), App.DEBUG_LEVEL.ERROR); //e.printStackTrace();
                        }
                        showCountdownDialog("设置", "正在设置初始力值，请等待机器设置完成，不要拉动弹力带！", 3,"确定", "取消");
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    boolean isProgressCountQuited = false;
    AlertDialog alertDialog_show = null;
    private void showCountdownDialog(final String title, String detail, final int count_s, String enter, String cancel) throws NoSuchFieldException, IllegalAccessException {
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(LoginActivity.this);
        LayoutInflater inflater = LayoutInflater.from(LoginActivity.this);
        View view = inflater.inflate(R.layout.countdown_dialog, null);
        alertDialog.setView(view);
        alertDialog.setTitle(title);
        TextView textView = (TextView) view.findViewById(R.id.dialog_text);
        textView.setText(detail);
        final RoundProgressBar roundProgressBar = (RoundProgressBar) view.findViewById(R.id.dialog_progressBar);
        roundProgressBar.setStyle(false);
        roundProgressBar.setCricleColor(Color.RED);
        roundProgressBar.setCricleProgressColor(Color.BLUE);
        roundProgressBar.setMax(count_s*1000);
//        /* 确定 */
//        alertDialog.setPositiveButton(enter,
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });
//        /* 取消 */
//        alertDialog.setNegativeButton(cancel,
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        initForce_switch.setChecked(false);
//                    }
//                });

        alertDialog_show = alertDialog.show();
        //通过反射修改title字体大小和颜色
        Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
        mAlert.setAccessible(true);
        Object mAlertController = mAlert.get(alertDialog_show);
        Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
        mTitle.setAccessible(true);
        final TextView mTitleView = (TextView) mTitle.get(mAlertController);
        //mTitleView.setTextSize(32);
        //mTitleView.setTextColor(Color.RED);
        isProgressCountQuited = false;
        class ProgressHandler extends Handler {
            Bundle bundle;     //建立一个装数据用的箱子

            public ProgressHandler() { }
            public ProgressHandler(Looper L) {
                super(L);
            }

            @Override
            public void handleMessage(Message msg) {       //当有从另一线程传来的消息时 这里开始运行
                super.handleMessage(msg);
                bundle  = msg.getData();                    //msg是从另一线程传来的数据 ，先用箱子捕获数据
                int time_S = bundle.getInt("time_S");
                mTitleView.setText(title + ": " + (count_s - time_S) + "S");
            }
        }
        final ProgressHandler progressHandler = new ProgressHandler();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int count_i = 0;
                int progress = 0;
                Message message;
                Bundle bundle = new Bundle();
                while (true){
                    if(isProgressCountQuited)
                        return;

                    count_i++;
                    App.sleep_ms(100);
                    progress = count_s*1000 - count_i*100;
                    roundProgressBar.setProgress(progress);
                    if(count_i %10 == 0){
                        bundle.clear();
                        bundle.putInt("time_S", count_i/10);
                        message = progressHandler.obtainMessage();
                        message.setData(bundle);
                        progressHandler.sendMessage(message);
                    }
                    if(progress <= 0){
                        if(null != alertDialog_show)
                            alertDialog_show.dismiss();
                        // 倒计时结束
                        return;
                    }
                }
            }
        });
        thread.start();
    }

    void startOneTest(){
        TestproSetup.currentPlan = spinner_plan.getSelectedItemPosition()+1;
        TestproSetup.LoadSetup();
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, MainActivity.class);
        LoginActivity.this.startActivity(intent);
    }

    private void layout_switchShow(boolean normal){
        if(normal){
            layout_freedom.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0));
            layout_profession.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
        }else{
            layout_freedom.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
            layout_profession.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0));
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layout_freedom.getLayoutParams();
            params.setMargins(110, 0, 0, 0);
            layout_freedom.setLayoutParams(params);
        }
    }

    private void showNormalDialog(){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        //normalDialog.setIcon(R.drawable.curve);
        normalDialog.setTitle("未输入用户ID");
        normalDialog.setMessage("你确定以游客形式进行登录吗?\n注：测试数据不会保存！");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startOneTest();
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        App.toast("测试已取消", App.DEBUG_LEVEL.INFO);
                    }
                });
        // 显示
        normalDialog.show();
    }

    @Override
    protected void onResume(){
        super.onResume();
        if(!App.isDebug_UI_now){
            if(false == isConnected) {

                if(0 != connection.requestPermission()){        // USB转串口打开失败
                    Toast.makeText(this, "申请设备连接...", Toast.LENGTH_SHORT).show();
                    connection.requestRS232Serial("/dev/ttyS1", 115200);
                }else{
                    Toast.makeText(this, "申请USB设备连接...", Toast.LENGTH_SHORT).show();
                }
            }
        }
        List<String> strList_group = new ArrayList<String>();
        TestproSetup.LoadPlanName();
        for(int i=0; i<10; i++)
            strList_group.add(TestproSetup.plan_str[i]);
        ArrayAdapter<String> adapter_group = new ArrayAdapter<String>(this, R.layout.spinner_display_style, R.id.txtvwSpinner, strList_group);
        adapter_group.setDropDownViewResource(R.layout.spinner_dropdown_style);
        spinner_plan.setAdapter(adapter_group);

        /* 清理游客测试文档 */
        CreatePDF.ManageFile();
    }

    @Override
    protected void onDestroy() {
        Toast.makeText(this, "login destroy", Toast.LENGTH_SHORT).show();
        if (connection != null) {
            connection.disconnect();
        }
        super.onDestroy();
    }

    long index = 0;
    private void initLineChart(){
        /* 模拟曲线 */
        final LineChartView chart_line;
        final LineChartData lineChartData = new LineChartData();
        final LINE forceLine;
        List<Line> chartLines = new ArrayList<Line>();
        Timer timer;
        TimerTask timerTask;
        final int timeIntval = 20;

        chart_line = (LineChartView) findViewById(R.id.login_chart);
        forceLine = new LINE(chartLines, Color.parseColor("#00BFFF"));
        forceLine.setMaxLineLen(500);

        lineChartData.setLines(chartLines);
        //坐标轴
        Axis axisX = new Axis();            //X轴
        axisX.setHasTiltedLabels(true);     //X坐标轴字体是斜的显示还是直的，true是斜的显示
        //axisX.setTextColor(Color.BLUE);    //设置字体颜色
        //axisX.setName("date");            //表格名称
        axisX.setTextSize(10);              //设置字体大小
        axisX.setMaxLabelChars(8);          //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        //axisX.setValues(mAxisXValues);      //填充X轴的坐标名称
        lineChartData.setAxisXBottom(axisX);         //x 轴在底部
        //data.setAxisXTop(axisX);          //x 轴在顶部
        axisX.setHasLines(true);            //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();            //Y轴
        axisY.setName("");                  //y轴标注
        axisY.setTextSize(10);              //设置字体大小
        lineChartData.setAxisYLeft(axisY);           //Y轴设置在左边

        //设置行为属性，支持缩放、滑动以及平移
        chart_line.setInteractive(true);
        chart_line.setZoomEnabled(false);
        //chart_line.setMaxZoom((float) 4);//最大方法比例
        chart_line.setContainerScrollEnabled(false, ContainerScrollType.HORIZONTAL);
        chart_line.setLineChartData(lineChartData);

        chart_line.setVisibility(View.VISIBLE);

        class ProgressHandler extends Handler {
            Bundle bundle;     //建立一个装数据用的箱子
            public ProgressHandler() { }
            public ProgressHandler(Looper L) {
                super(L);
            }

            @Override
            public void handleMessage(Message msg) {       //当有从另一线程传来的消息时 这里开始运行
                super.handleMessage(msg);
                bundle  = msg.getData();                    //msg是从另一线程传来的数据 ，先用箱子捕获数据
                float data_Y = bundle.getFloat("data_Y");

                forceLine.add(index, data_Y);
                chart_line.setLineChartData(lineChartData);
            }
        }
        final ProgressHandler progressHandler = new ProgressHandler();

        timer = new Timer();
        final Bundle bundle = new Bundle();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                index = index+1;
                bundle.putFloat("data_Y", getYvalue(index));
                Message message = progressHandler.obtainMessage();
                message.setData(bundle);
                progressHandler.sendMessage(message);
            }
        };
        timer.schedule(timerTask, timeIntval, timeIntval);
    }

    int maxSin = 5;
    float getYvalue(long time_ms){
        float a = (float)((time_ms%100)/50.0*Math.PI);
        if(time_ms%100 == 0){
            maxSin = (int)(Math.random()*10)+5;
        }
        float value = (float)((maxSin) * Math.sin(a));
        return value;
    }
}
